package com.metadata_system.ai.service;

import com.metadata_system.ai.request.DatabaseListRequest;
import com.metadata_system.ai.request.ProjectListRequest;
import com.metadata_system.ai.request.ProjectNodeListRequest;
import com.metadata_system.ai.response.DatabaseResponse;
import com.metadata_system.ai.response.ProjectNodeResponse;
import com.metadata_system.ai.response.ProjectResponse;
import com.metadata_system.common.db.entity.Database;
import com.metadata_system.common.db.entity.Project;
import com.metadata_system.common.db.entity.ProjectNode;
import com.metadata_system.common.db.mapper.DatabaseMapper;
import com.metadata_system.common.db.mapper.ProjectMapper;
import com.metadata_system.common.db.mapper.ProjectNodeMapper;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.dto.SelectItem;
import com.metadata_system.common.enums.AllConst;
import com.metadata_system.common.utils.DateTimeUtil;
import com.metadata_system.common.utils.MyUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("aiProjectService")
public class ProjectService {
    @Autowired(required = false)
    DatabaseMapper databaseMapper;
    @Autowired(required = false)
    ProjectMapper projectMapper;
    @Autowired(required = false)
    ProjectNodeMapper projectNodeMapper;


    public ApiResult getDatabaseList(DatabaseListRequest listRequest) {
        Example example = new Example(Database.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(listRequest.getUpdatedTime())) {
            try {
                Date updatedTime = DateTimeUtil.parseToDate(listRequest.getUpdatedTime(), DateTimeUtil.FMT_yyyyMMddHHmmss);
                criteria.andGreaterThan("updatedTime", updatedTime);
            } catch (Exception e) {
                return ApiResult.error("时间格式错误");
            }
        }
        listRequest.setOrder(example, "updatedTime");
        int count = this.databaseMapper.selectCountByExample(example);
        List<Database> databases = new ArrayList<>();
        if (count > 0) {
            databases = databaseMapper.selectByExampleAndRowBounds(example, listRequest.getRowRunds());
        }
        return ApiResult.syncList(DatabaseResponse.fromEntity(databases), count, new ArrayList<>());
    }

    public ApiResult getProjectList(ProjectListRequest listRequest) {
        Example example = new Example(Project.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(listRequest.getUpdatedTime())) {
            try {
                Date updatedTime = DateTimeUtil.parseToDate(listRequest.getUpdatedTime(), DateTimeUtil.FMT_yyyyMMddHHmmss);
                criteria.andGreaterThan("updatedTime", updatedTime);
            } catch (Exception e) {
                return ApiResult.error("时间格式错误");
            }
        }
        if (listRequest.getDatabaseId() != null) {
            criteria.andEqualTo("databaseId", listRequest.getDatabaseId());
        }
        if (listRequest.getMetadataId() != null) {
            criteria.andEqualTo("metadataId", listRequest.getMetadataId());
        }
        if (listRequest.getType() != null) {
            criteria.andEqualTo("type", listRequest.getType());
        }
        listRequest.setOrder(example, "updatedTime");
        int count = this.projectMapper.selectCountByExample(example);
        List<Project> projects = new ArrayList<>();
        if (count > 0) {
            projects = projectMapper.selectByExampleAndRowBounds(example, listRequest.getRowRunds());
        }
        return ApiResult.syncList(ProjectResponse.fromEntity(projects), count, new ArrayList<>());
    }


    public ApiResult getProjectNodeList(ProjectNodeListRequest listRequest) {
        Example example = new Example(ProjectNode.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(listRequest.getUpdatedTime())) {
            try {
                Date updatedTime = DateTimeUtil.parseToDate(listRequest.getUpdatedTime(), DateTimeUtil.FMT_yyyyMMddHHmmss);
                criteria.andGreaterThan("updatedTime", updatedTime);
            } catch (Exception e) {
                return ApiResult.error("时间格式错误");
            }
        }
        if (listRequest.getProjectId() != null) {
            criteria.andEqualTo("projectId", listRequest.getProjectId());
        }
        if (listRequest.getMetadataNodeId() != null) {
            criteria.andEqualTo("metadataNodeId", listRequest.getMetadataNodeId());
        }
        listRequest.setOrder(example, "updatedTime");
        int count = this.projectNodeMapper.selectCountByExample(example);
        List<ProjectNode> projectNodes = new ArrayList<>();
        if (count > 0) {
            projectNodes = projectNodeMapper.selectByExampleAndRowBounds(example, listRequest.getRowRunds());
        }
        return ApiResult.syncList(ProjectNodeResponse.fromEntity(projectNodes), count, new ArrayList<>());
    }


    public ApiResult getProjectNodeDataList(Integer projectId, Integer metadataNodeId, Integer page, Integer pageSize, Map<String, Object> searchMap, String sortProp, String sortOrder) {
        ProjectNode projectNode = this.projectNodeMapper.selectOne(ProjectNode.builder()
                .projectId(projectId)
                .metadataNodeId(metadataNodeId)
                .build());
        if (projectNode == null) {
            return ApiResult.error("项目节点 不存在");
        }
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1 || pageSize > 500) {
            pageSize = 10;
        }

        List<String> constionList = MyUtil.getConditionList(searchMap, projectNode);

        Integer limit = pageSize;
        Integer offset = (page - 1) * pageSize;

        if (StringUtils.isBlank(sortProp) || !Arrays.asList("id", "createdTime").contains(sortProp)) {
            sortProp = "id";
        }
        if (!Arrays.asList("ASC", "DESC").contains(sortOrder.toUpperCase())) {
            sortOrder = "desc";
        }
        if (StringUtils.isBlank(sortOrder)) {
            sortOrder = "desc";
        }

        String order = " order by " + sortProp + " " + sortOrder + " ";
        int total = this.projectMapper.getNodeDataTotal(projectId, metadataNodeId, constionList);
        List<Map<String, Object>> nodeDataList = new ArrayList<>();
        if (total > 0) {
            nodeDataList = this.projectMapper.getNodeDataList(projectId, metadataNodeId, offset, limit, constionList, order);
        }
        return ApiResult.syncList(nodeDataList, total, new ArrayList<>());
    }


}
